<template>
  <div
    id="app"
    @click="appClick"
    @mousedown="appDown"
  >
    <!-- 默认导航条 @mousedown="appDown" -->
    <window-header v-if="!(screenShotsStatus && screenImgSrc!=='' )"/>

    <!-- 路由加载 -->
    <router-view v-show="!(screenShotsStatus && screenImgSrc!=='' )"/>

    <!-- 截图组件 -->
    <screenShots v-if="(screenShotsStatus && screenImgSrc!=='' )"/>

    <!-- 全局加载状态 -->
    <status
      v-show="(loadingLabel!=='' && !(screenShotsStatus && screenImgSrc!=='' ) )"
      :type="2"
      :label="loadingLabel"
      :mask="true"
    />

    <!-- 问题反馈的提示 -->
    <div
        class="qa-notice"
        v-if="(qaNotice && !(loadingLabel!=='' && !(screenShotsStatus && screenImgSrc!=='' ) ) )"
    >
      <img class="qa-notice-img0" src="./assets/image/qa_notice0.png" alt="反馈问题">
      <img class="qa-notice-img1" src="./assets/image/qa_notice1.png" alt="知道了" @click="qaNotice=false">
    </div>

  </div>
</template>

<script>
import Vue from 'vue'
import activeShowMixin from "./mixin/activeShow.mixin";
import windowHeader from "./components/public/windowHeader";
import screenShots from "./components/function/screenShots";
import status from "./components/public/status";
import { baseURL } from "./libs/http";
import bus from './libs/event-bus'

import { socket } from "./libs/socketClass.js";

export default {
  components: { windowHeader, screenShots, status },
  mixins: [activeShowMixin],
  data() {
    return {
      acceptArray: [
        ".png",
        ".jpg",
        ".jpeg",
        ".bmp",
        ".pdf",
        ".tif",
        ".tiff"
      ], // ".pdf,.jpg,.jpeg,.png,.bmp,.tif,.tiff"
      screenStatus: false,
      qaNotice: false, // 问题反馈的遮罩提示
    };
  },
  watch: {
    dirId(newValue) {
      try {
        // 暂时关闭全局上传功能
        return

        let url = `${baseURL}${this.$url.uploadFile.url}/${
          this.userId
        }/${newValue}`;
        let _this = this;

        const dropUploadCallback = function(fileList) {
          let file = fileList[0],
            typeAllowed = false;
          // 检测文件的合法性;
          for (let i = 0; i < _this.acceptArray.length; i++) {
            const item = _this.acceptArray[i];
            if (
              file.name.indexOf(item) > -1 ||
              file.name.indexOf(item.toUpperCase()) > -1
            ) {
              typeAllowed = true;
              break;
            }
          }
          if (!typeAllowed) {
            _this.$message.warn(
              `不支持的文件类型，请上传${_this.acceptArray}文件！`
            );
            return;
          }
          if (file.size > 20971520) {
            // 20971520字节等于20
            _this.$message.warn("文件大小不能超过20M！");
            return false;
          }
          _this.$message.loading("正在上传..", 0);
          let xhr = new XMLHttpRequest();
          //成功回调
          xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
              _this.$message.destroy();
              if (
                (xhr.status >= 200 && xhr.status < 300) ||
                xhr.status == 304
              ) {
                // 关闭上传中loading提示
                _this.$message.success(`${file.name} 上传成功！`);
                _this.setNeedRefreshList(true);
              } else {
                // console.log("上传服务异常===>", xhr.status);
                _this.$message.error(`${file.name} 上传失败，请重新上传！`);
              }
            }
          };
          xhr.open("post", url, true);
          xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
          let fd = new FormData();
          fd.append("files", file);
          xhr.send(fd);
        };

        let dropUpload = new DropUpload();
        dropUpload.stopDefaultEvent();
        dropUpload.bindDropEvent(document, dropUploadCallback);
      } catch (error) {
        // console.log(error);
      }
    },
  },
  created() {
    this.setLoadingLabel(`加载中...`);
    localStorage.setItem('advancedFunButtonStatus', 1);

    // 通信连接
    Vue.prototype.$webSC = new socket( window.GLOBAL_CONFIG.socket, this.setWebSC );
    this.webSCOpen(); // 客户端通信建立方法

    // userId 参数一定放路由的最后
    // let reg = new RegExp("(^|&)" + "userId" + "=([^&]*)(&|$)", "i");
    // let url = location.href.split("?")[1];
    // let advancedFun = url.split("&")[0];
    // let r = url?url.match(reg):undefined;
    let userId = this.$route.query.userId;
    let advancedFun = this.$route.query.advancedFun;
    // 该系统可以使用高级功能
    if(advancedFun === 'true'){
      this.setAdvancedFunStatus(1);
    }

    if (userId) {
      this.setUserInfo({
        userId: unescape(userId)
      });
    } else {
      this.$message.error(`未检测到userID,当前地址为：${location.href}`);
    }

    // console.log( 'app created', localStorage.getItem("isQaNotice") );
    if( localStorage.getItem("isQaNotice") == null ){
      this.qaNotice = true;
      localStorage.setItem("isQaNotice", "true");
    }

  },
  mounted() {
    let that = this;
    window.onresize = () => {
      that.setResizeStatus( (new Date()).valueOf() );
      bus.$emit('getScreenShotsRect')
    }
    //

  },
  destroyed() {
    window.onresize = null;

    this.$webSC.webSCClose().then(res => {
    }).catch(error => { });
  },
  computed: {
    dirId() {
      return this.$store.state.user.dirId;
    },
    userId() {
      return this.$store.state.user.userId;
    },
    screenShotsStatus() {
      if( this.$store.state.status.screenShotsStatus ){
        this.setFileSearchVisible(false);
        this.setSelectionBtnVisible(false);
        this.setCaptureVisible(false);
        this.setExportVisible(false);
        this.setFileDownloadVisible(false);
        this.setQaVisible(false);
      }
      return this.$store.state.status.screenShotsStatus;
    },
    screenImgSrc() {
      return this.$store.state.file.screenImgSrc;
    },
    loadingLabel() {
      if(this.$store.state.status.loadingLabel !== ''){
        // 将弹窗收起
        this.setFileSearchVisible(false);
        this.setSelectionBtnVisible(false);
        this.setCaptureVisible(false);
        this.setExportVisible(false);
        this.setFileDownloadVisible(false);
        this.setQaVisible(false);
      }
      return this.$store.state.status.loadingLabel;
    },
  },
  methods: {
    // 通信建立
    webSCOpen() {
      // 老版本联通方法
      this.$webSC.webSCOpen().then(res => {
        // 通信成功
        console.log(res);
        if( localStorage.getItem("screenKey") ){
          if( localStorage.getItem("screenKey") !== ''  ){
            if(localStorage.getItem("screenKey").length){
              let char = localStorage.getItem("screenKey").slice(0, 1).replace(/[^A-Za-z]/g,'').toUpperCase()||'S';
              localStorage.setItem("screenKey", char);
              this.screenKeyChange(char);
              this.setScreenInputChar(char);
            }
            else{
              localStorage.setItem("screenKey", "S");
              this.screenKeyChange('S');
              this.setScreenInputChar('S');
            }
          }
          else{
            localStorage.setItem("screenKey", "S");
            this.screenKeyChange('S');
            this.setScreenInputChar('S');
          }
        }
        else{
          localStorage.setItem("screenKey", "S");
          this.screenKeyChange('S');
          this.setScreenInputChar('S');
        }

      }).catch(error => {
        // 通信失败
        console.log(error, '2秒后重新连接');
        // setTimeout(() => {
        //   this.webSCOpen();
        // }, 500);
      });
    },
    // screenKey 校验
    screenKeyChange(value) {
      let pay = {
          code: 3,
          cmd: "Hot_key",
          param: `Alt+${value}`,
        }

      this.$webSC.webSCAsync(pay).then(res =>{
        // console.log( 'app screenKeyChange', pay, res);
        if(res)
        if(res.cmd !== 'Hot_key')return

        if( (res.status == 200 || res.status == 400) && !this.$store.state.status.screenCanUse ){
          this.setScreenCanUse(true);
        }else if( res.status == 500 && this.$store.state.status.screenCanUse ){
          this.setScreenCanUse(false);
        }

      });

    },
    // 全局点击事件
    appClick() {
      // 搜索弹窗打开
      if( this.$store.state.status.fileSearchVisible ){
        this.setFileSearchVisible(false);
      }

      if( this.$store.state.status.selectionBtnVisible ){
        this.setSelectionBtnVisible(false);
      }

      if( this.$store.state.status.fileDownloadVisible ){
        this.setFileDownloadVisible(false);
      }

    },
    appDown(){
      if( this.$store.state.status.qaVisible ){
        this.setQaVisible(false);
      }
    },
  },
};
</script>

<style lang="less">

body {
  background-color: #eee !important;
  overflow: hidden;
}

#app {
  height: 100%;
  display: flex;
  flex-direction: column;
  -webkit-user-select:none;
  -moz-user-select:none;
  -ms-user-select:none;
  user-select:none;
  position: relative;
  min-width: 1280px;
  min-height: 696px;
}

.qa-notice{
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 998;
  overflow: hidden;
  background-color: rgba(0, 0, 0, 0.65);
}
.qa-notice-img0{
  position: absolute;
  top: 0;
  right: 0;
}
.qa-notice-img1{
  position: absolute;
  top: 260px;
  right: 70px;
  cursor: pointer;
}
</style>

<style>
/*
  <div class='loading' v-show="(this.$store.state.status.loadingLabel!=='' && !(this.screenShotsStatus && this.$store.state.file.screenImgSrc!=='' ) )">
    <div class='loading-bg'></div>
    <status
      class='loading-status'
      :type="0"
      :label="this.$store.state.status.loadingLabel"
    />
  </div>
  .loading{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 999;
    overflow: hidden;
  }

  .loading-bg{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: #eee;
    opacity: 0.7;
  }

  .loading-status{
    position: absolute;
    top: calc( 50% - 75px );
    left: calc( 50% - 75px );
  }
 */
</style>
